import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { get } from '@/utils/service'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const member = ref(null)
  const openId = ref(localStorage.getItem('openId')) // 从 localStorage 读取初始 openId
  const isInitialized = ref(false)

  // Getter
  const isAuthenticated = computed(() => !!openId.value)

  // Actions
  async function login(openId) {
    try {
      const response = await get('/memberWechatNew/', { openId: openId })
      member.value = response.data.member
      openId.value = response.data.openId
      localStorage.setItem('openId', response.data.openId) // 存储 openId
      // 可能还需要存储其他用户信息到 localStorage 或 sessionStorage
      return response
    } catch (error) {
      logout()
      throw error
    }
  }

  async function logout() {
    member.value = null
    openId.value = null
    localStorage.removeItem('openId') // 移除 openId
    localStorage.removeItem('memberInfo') // 如果有的话，移除用户信息
    // 清除其他用户相关存储
  }

  async function initialize() {
    // 页面刷新时，如果有 openId，尝试获取用户信息
    if (openId.value) {
      try {
        const memberInfo = await api.getmemberInfo()
        member.value = memberInfo
      } catch (error) {
        // openId 可能已失效
        console.error('Failed to fetch member info:', error)
        logout()
      }
    }
    isInitialized.value = true
  }

  return {
    member,
    openId,
    isInitialized,
    isAuthenticated,
    login,
    logout,
    initialize,
  }
})
